<template>
  <div>
    <div class="search">
      <span>文章标题</span>
      <el-input
        style="width: 220px"
        v-model="params.searchTitle"
        placeholder="请输入(模糊查询)"
      ></el-input>
      <span>发布日期</span>
      <el-date-picker
        v-model="value"
        type="daterange"
        align="right"
        unlink-panels
        value-format="yyyy-MM-dd 00:00:00"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      >
      </el-date-picker>
      <span></span>
      <el-button type="primary" @click="search"
        ><i class="el-icon-search"> 查询</i></el-button
      >
      <span></span
      ><el-button @click="reset"
        ><i class="el-icon-refresh-right"> 重置</i></el-button
      >
    </div>
    <div class="body">
      <div class="addtext">
        <el-button type="primary" @click="setNewText">添加文章</el-button>
        <!-- 需要补充富集表 -->

        <el-dialog
          top="0"
          :visible.sync="dialogFormVisible"
          fullscreen
          :show-close="false"
        >
          <el-form
            :model="addtext"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <div class="header">
              <h2>写文章</h2>
              <el-form-item>
                <el-button @click="resetForm()">取消</el-button>
                <el-button type="primary" @click="submitForm()"
                  ><i class="el-icon-s-promotion">发布</i></el-button
                >
              </el-form-item>
            </div>
            <el-form-item label="标题" prop="title">
              <el-input v-model="addtext.title"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <div style="border: 1px solid #ccc">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  style="height: 500px; overflow-y: hidden"
                  v-model="html"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
                
                />
              </div>
            </el-form-item>
            <el-form-item label="封面" required prop="titleImage">
              <template>
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :http-request="setimg"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  auto-upload:true
                >
                  <img
                    v-if="addtext.titleImage"
                    :src="addtext.titleImage"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-form-item>
            <el-form-item label="摘要" prop="description">
              <el-input v-model="addtext.description"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="addtext.categoryId" placeholder="请选择">
                <el-option
                  v-for="item in categorylist"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签" prop="tags">
              <el-select v-model="addtext.tags" multiple placeholder="请选择">
                <el-option
                  v-for="item in taglist"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-dialog>
        <!--  -->
      </div>
      <div class="showbox" style="line-height: 0">
        <el-table :data="datalist" style="width: 100%" stripe>
          <el-table-column label="标题" width="300" prop="title">
          </el-table-column>
          <el-table-column label="预览图" width="200">
            <template slot-scope="scope">
              <img :src="scope.row.titleImage" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="发布时间" width="180" prop="createTime">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                ><i>编辑</i></el-button
              >
              <el-button size="mini" @click="handleSee(scope.$index, scope.row)"
                ><i>预览</i></el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                ><i>删除</i></el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.current"
          :page-sizes="[10, 20, 50]"
          :page-size="params.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { text, textDelete, textAdd } from "../../../../units/htapi";
export default {
  //
  components: { Editor, Toolbar },
  //
  data() {
    return {
      params: {
        current: 1, //页面号
        size: 10, //页面显示条数
        searchTitle: "", //搜索值
        startDate: "", //开始时间
        endDate: "", //结束时间
      },
      count: 0, //总页数
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      }, //日期选择器
      dialogFormVisible: false,
      value: "",
      datalist: [], //存储渲染数据的列表
      //
      editor: null,
      html: "<p>请在此输入内容</p>",
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容..." },
      mode: "default", // or 'simple'
      //
      addtext: {
        content: "", //富文本
        description: "", //摘要
        // id:null,
        title: "", //标题
        titleImage: "", //封面图
        tags: [], //标签
        categoryId: "", //分类id
      },
      categorylist: [], //分类的转换数组
      taglist: [], //多选的标签转换数组,
      categoryLoaded: false, //分类和标签缓存避免多次获取
      tagLoaded: false,
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          { min: 0, max: 40, message: "", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入文章摘要", trigger: "change" },
        ],
        tags: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个标签",
            trigger: "change",
          },
        ],
        categoryId: [
          { required: true, message: "请选择分类形式", trigger: "change" },
        ],
      },
      imageUrl: "",
      //
    };
  },
  created() {
    this.getdata();
  },
  methods: {
    async getdata() {
      this.loading = true;
      try {
        let res = await text(this.params);
        // console.log(res);
        this.datalist = res.data.data.records; //传入数据列表
        this.count = res.data.data.total; //传入数据条数
      } catch (error) {
        this.$message.error("数据加载失败");
        console.log(error, "这是一个错误");
      } finally {
        this.loading = false; // 无论成功失败都关闭loading
      }
    },
    handleEdit(index, row) {
      // row.id
      console.log(index, row);
      this.dialogFormVisible = true



    }, //编辑按钮
    handleSee(index, row) {
      //预览
      this.$router.push({
        name: "indexmore",
        params: {
          id: row.id,
        },
      });

      console.log(index, row);
    }, //预览
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await textDelete({ articleId: row.id });
            this.getdata();
            this.$message.success("删除成功");
          } catch (error) {
            console.log("删除出错", error);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //   console.log(index, row);
    //删除按钮

    search() {
      if (this.value && this.value.length === 2) {
        this.params.startDate = this.value[0];
        this.params.endDate = this.value[1] || this.value[0]; // 处理结束日期为空的情况
      } else {
        this.params.startDate = "";
        this.params.endDate = "";
      }

      this.getdata(); //重新获取数据
    },
    reset() {
      // 重置按钮
      this.params = {
        current: 1,
        size: 10,
        searchTitle: "",
        startDate: "",
        endDate: "",
      };
      this.value = ""; // 重置日期选择器
      this.getdata();
    },
    handleSizeChange(val) {
      //分页器
      this.params.size = val;
      // console.log(`每页 ${val} 条`);
      this.params.current = 1; // 切换每页条数时，重置到第一页
      this.getdata(); // 重新加载数据
    },
    handleCurrentChange(val) {
      this.params.current = val;
      // console.log(`当前页: ${val}`);
      this.getdata(); // 重新加载数据
    },
    //
    setNewText() {
      //添加文章按钮
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.getCategory(); //拉去分类
        this.getTag(); //拉去标签
      });
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      
      
    },
    submitForm() {
      //发布按钮
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          this.addtext.content = this.html; //将富文本内容添加同步到表单上
          let res = await textAdd(this.addtext);
          this.getdata();
          console.log(res);
          if (res.data.success) {
            this.$message.success("发布成功");
            this.dialogFormVisible = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs["ruleForm"].resetFields();
      this.html = "<p>请在此输入内容</p>";
      this.dialogFormVisible = false;
    },
    handleAvatarSuccess(res, file) {
      //上传成功时执行的函数
      this.addtext.titleImage = URL.createObjectURL(file.raw);
      // console.log(res);
      // console.log(file,21323121321321);
      // console.log(this.addtext);
    },
    
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 5; //限制上传的大小

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isLt2M;
    },
    //
    async getCategory() {
      //拉去分类
      let res = await this.$axios.post("/api/admin/category/select/list");
      // console.log(res);
      this.categorylist = res.data.data;
      this.categoryLoaded = true;
    },
    async getTag() {
      //拉取标签
      let res = await this.$axios.post("/api/admin/tag/select/list");
      // console.log(res);
      this.taglist = res.data.data;
      this.tagLoaded = true;
    },
    async setimg(a){
      // console.log(a,'aaaa');
      const form = new FormData()
      form.append('file',a.file)
      let res =  await this.$axios.post('/api/admin/file/upload',form)
      this.addtext.titleImage = res.data.data.url
      // console.log(res,'rereres');
      
    }
  },
  //
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
  //
};
</script>

<style scoped lang="scss">
@import "@wangeditor/editor/dist/css/style.css";
.search {
  width: 100%;
  height: 80px;
  background-color: #fff;
  margin-bottom: 20px;
  line-height: 20px;
  text-align: left;
  box-sizing: border-box;
  padding: 20px;
  span {
    margin-left: 20px;
    margin-right: 10px;
  }
}
.body {
  width: 100%;
  height: auto;
  min-height: 200px;
  background-color: #fff;
  box-sizing: border-box;
  padding: 20px;
  .addtext {
    line-height: 20px;
    width: 100%;
    height: 40px;
    text-align: left;
    box-sizing: border-box;
    // background-color: red;
    margin-bottom: 20px;
  }
  .showbox {
    // width: 100%;
    // height: 500px;
    // background-color: red;
    img {
      width: 50px;
      height: 50px;
    }
  }
  .page {
    margin-top: 20px;
  }
}
::v-deep .el-dialog__header {
  padding: 0;
  height: 0;
}
::v-deep .el-dialog__body {
  padding: 10px 20px;
}
.header {
  display: flex;
  justify-content: space-between;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>